package com.zaaach.citypicker.adapter;


import com.zaaach.citypicker.ResourceTable;
import com.zaaach.citypicker.model.City;
import com.zaaach.citypicker.model.HotCity;
import com.zaaach.citypicker.model.LocateState;
import com.zaaach.citypicker.model.LocatedCity;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.*;
import ohos.agp.utils.TextTool;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

import java.util.List;
import java.util.Optional;

/**
 * @Author: Bro0cL
 * @Date: 2018/2/5 12:06
 */
public class CityListAdapter extends BaseItemProvider {
    private static final int VIEW_TYPE_LOCATION = 10;
    private static final int VIEW_TYPE_HOT = 11;
    private static final int VIEW_TYPE_DEFAULT = 12;
    private Context mContext;
    private List<City> mData;
    private List<HotCity> mHotData;
    private int locateState;
    private InnerListener mInnerListener;
    private boolean stateChanged;
    private boolean autoLocate;


    public CityListAdapter(List<City> list, List<HotCity> hotData, int state,Context slice) {
        this.mData = list;
        this.mContext = slice;
        this.mHotData = hotData;
        this.locateState = state;
    }

    public void autoLocate(boolean auto) {
        autoLocate = auto;
    }


    public void updateData(List<City> data) {
        this.mData = data;
        notifyDataChanged();
    }
    public void updateHotData(List<HotCity> data) {
        this.mHotData = data;
        notifyDataChanged();
    }
    public void updateLocateState(LocatedCity location, int state, ListContainer listContainer) {
        mData.remove(0);
        mData.add(0, location);
        stateChanged = !(locateState == state);
        locateState = state;
        if (listContainer.getItemPosByVisibleIndex(0) == 0) {
            refreshLocationItem();
        }
    }

    public void refreshLocationItem() {
        //如果定位城市的item可见则进行刷新.
        if (stateChanged) {
            stateChanged = false;
            notifyDataSetItemChanged(0);
        }
    }

    /**
     * 滚动RecyclerView到索引位置
     *
     * @param index index
     * @param lc  ListContainer
     */
    public void scrollToSection(String index, ListContainer lc) {
        if (mData == null || mData.isEmpty()) return;
        if (TextTool.isNullOrEmpty(index)) return;
        int size = mData.size();
        for (int i = 0; i < size; i++) {
            if (TextTool.isEqual(index.substring(0, 1), mData.get(i).getSection().substring(0, 1))) {
                if (lc != null) {
                    lc.scrollTo(i);
                    if (TextTool.isEqual(index.substring(0, 1), "定")) {
                        //防止滚动时进行刷新
                        new EventHandler(EventRunner.getMainEventRunner()).postTask(new Runnable() {
                            @Override
                            public void run() {
                                if (stateChanged) notifyDataSetItemChanged(0);
                            }
                        }, 1000);
                    }
                    return;
                }
            }
        }
    }

    // 用于保存列表项中的子组件信息
    public static class DefaultViewHolder {
        Text name;
        StackLayout header;
        Text headerText;
        DefaultViewHolder(Component itemView) {
            header = (StackLayout) itemView.findComponentById(ResourceTable.Id_header_layout);
            headerText = (Text) itemView.findComponentById(ResourceTable.Id_header);
            name = (Text) itemView.findComponentById(ResourceTable.Id_cp_list_item_name);
        }
    }

    public static class HotViewHolder {
        ListContainer mRecyclerView;
        StackLayout header;
        Text headerText;
        HotViewHolder(Component itemView) {
            header = (StackLayout) itemView.findComponentById(ResourceTable.Id_header_layout);
            headerText = (Text) itemView.findComponentById(ResourceTable.Id_header);
            mRecyclerView = (ListContainer) itemView.findComponentById(ResourceTable.Id_cp_hot_list);
        }
    }

    public static class LocationViewHolder {
        StackLayout header;
        Text headerText;
        StackLayout container;
        Text current;

        LocationViewHolder(Component itemView) {
            header = (StackLayout) itemView.findComponentById(ResourceTable.Id_header_layout);
            headerText = (Text) itemView.findComponentById(ResourceTable.Id_header);
            container = (StackLayout) itemView.findComponentById(ResourceTable.Id_cp_list_item_location_layout);
            current = (Text) itemView.findComponentById(ResourceTable.Id_cp_list_item_location);
        }
    }
//
    @Override
    public int getItemComponentType(int position) {
        if (position == 0 && TextTool.isEqual("定", mData.get(position).getSection().substring(0, 1))) {
            return VIEW_TYPE_LOCATION;
        } else if (position == 1 && TextTool.isEqual("热", mData.get(position).getSection().substring(0, 1))){
            return VIEW_TYPE_HOT;
        }else {
            return VIEW_TYPE_DEFAULT;
        }

    }

    @Override
    public int getComponentTypeCount() {
        return 3;
    }

    @Override
    public int getCount() {
        return mData == null ? 0 : mData.size();
    }

    @Override
    public Object getItem(int position) {
        if (mData != null && position >= 0 && position < mData.size()) {
            return mData.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
        LocationViewHolder holder1= null;
        HotViewHolder holder2 = null;
        DefaultViewHolder holder3= null;
        final int pos = position;
        int type = getItemComponentType(position);
        City data = mData.get(position);
        if (component==null){
            switch (type) {
                case VIEW_TYPE_LOCATION:
                    component = LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_cp_list_item_location_layout, null, false);
                    holder1 = new LocationViewHolder(component);
                    component.setTag(holder1);
                    break;
                case VIEW_TYPE_HOT:
                    component = LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_cp_list_item_hot_layout, null, false);
                    holder2 = new HotViewHolder(component);
                    component.setTag(holder2);
                    break;
                case VIEW_TYPE_DEFAULT:
                    component = LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_cp_list_item_default_layout, null, false);
                    holder3 = new DefaultViewHolder(component);
                    component.setTag(holder3);
                    break;
                default:
                    break;
            }


        }else {
            switch (type) {
                case VIEW_TYPE_LOCATION:
                    holder1 = (LocationViewHolder) component.getTag();
                    break;
                case VIEW_TYPE_HOT:
                    holder2 = (HotViewHolder) component.getTag();
                    break;
                case VIEW_TYPE_DEFAULT:
                    holder3 = (DefaultViewHolder) component.getTag();
                    break;
            }
        }
        switch (type) {
            case VIEW_TYPE_LOCATION:
                switch (locateState) {
                    case LocateState.LOCATING:
                        holder1.current.setText(ResourceTable.String_cp_locating);
                        break;
                    case LocateState.SUCCESS:
                        holder1.current.setText(data.getName());
                        break;
                    case LocateState.FAILURE:
                        holder1.current.setText(ResourceTable.String_cp_locate_failed);
                        break;
                }
                holder1.header.setVisibility(Component.VISIBLE);
                holder1.headerText.setText("定位城市");
                holder1.container.setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        if (locateState == LocateState.SUCCESS) {
                            if (mInnerListener != null) {
                                mInnerListener.dismiss(pos, data);
                            }
                        } else if (locateState == LocateState.FAILURE){
                            locateState = LocateState.LOCATING;
                            notifyDataSetItemChanged(0);
                            if (mInnerListener != null){
                                mInnerListener.locate();
                            }
                        }
                    }
                });
                //第一次弹窗，如果未定位则自动定位
                if (autoLocate && locateState == LocateState.LOCATING && mInnerListener != null){
                    mInnerListener.locate();
                    autoLocate = false;
                }
                break;
            case VIEW_TYPE_HOT:
                holder2.header.setVisibility(Component.VISIBLE);
                holder2.headerText.setText("热门城市");
                GridListAdapter mAdapter = new GridListAdapter(mContext, mHotData);
                mAdapter.setInnerListener(mInnerListener);
//                TableLayoutManager tableLayoutManager = new TableLayoutManager();
//                tableLayoutManager.setColumnCount(3);
//                holder2.mRecyclerView.setLayoutManager(tableLayoutManager);
                holder2.mRecyclerView.setItemProvider(mAdapter);
                break;
            case VIEW_TYPE_DEFAULT:
                if (position>0&&TextTool.isEqual(data.getPinyin().substring(0,1),mData.get(position-1).getPinyin().substring(0,1))){
                    holder3.header.setVisibility(Component.HIDE);
                }else {
                    holder3.header.setVisibility(Component.VISIBLE);
                }
                holder3.headerText.setText(data.getPinyin().substring(0,1).toUpperCase());
                holder3.name.setText(data.getName());
                holder3.name.setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        if (mInnerListener != null) {
                            mInnerListener.dismiss(position, data);
                        }
                    }
                });
                break;
        }

        return component;
    }
    public void setInnerListener(InnerListener listener){
        this.mInnerListener = listener;
    }
}

